#!/usr/bin/env python3
"""
脚本名称：ch44_exe.py
功能描述： 演示 继承 VS 组合
作者：Gavin
创建日期：2022-05-06
版本：1.0
依赖库：无
使用方法： python ch44_exe.py
"""


# 1. 继承
# 继承方式1 隐式继承
class Parent(object):
    def implicit(self):
        print("PARENT implicit()")


class Child(Parent):
    # pass 并没有实际用途，表示是空代码块
    pass


print("继承方式1 隐式继承")
dad = Parent()
son = Child()
dad.implicit()
son.implicit()


# 继承方式2 显式覆写
class Parent2(object):
    def override(self):
        print("PARENT2 override()")


class Child2(Parent2):
    def override(self):
        print("CHILD2 override()")


print("\n\n继承方式2 显式重写")
dad2 = Parent2()
son2 = Child2()
dad2.override()
son2.override()


# 继承方式3  在运行前或运行后覆写，新增了 super 函数，可以在子类中调用父类的方法
class Parent3(object):
    def altered(self):
        print("PARENT3 altered()")


class Child3(Parent3):
    def altered(self):
        print("CHILD3, BEFORE PARENT altered()")
        # super()函数用于在子类中调用父类的方法。
        super(Child3, self).altered()
        print("CHILD3, AFTER PARENT altered()")


print("\n\n继承方式3  在运行前或运行后覆写")
dad3 = Parent3()
son3 = Child3()
dad3.altered()
son3.altered()


# 2. 组合
class Other(object):
    def override(self):
        print("OTHER override()")

    def implicit(self):
        print("OTHER implicit()")

    def altered(self):
        print("OTHER altered()")


class Child4(object):
    def __init__(self):
        self.other = Other()

    def implicit(self):
        self.other.implicit()

    def override(self):
        print("CHILD override()")

    def altered(self):
        print("CHILD, BEFORE OTHER altered()")
        self.other.altered()
        print("CHILD, AFTER OTHER altered()")


print("\n\n组合")

son = Child4()
son.implicit()  # OTHER implicit()
son.override()  # CHILD override()
son.altered()
# CHILD, BEFORE OTHER altered()
# OTHER altered()
# CHILD, AFTER OTHER altered()
